Ext.define('StaffServer.controller.SysUserController', {
	extend : 'Ext.app.Controller',

	models: ['SysUserModel', 'SysRoleModel'],
	stores: ['SysUserStore', 'SysRoleAllStore'],
	views:  ['sysUser.SysUserGrid', 'sysUser.SysUserMngr', 
	'sysUser.SysUserSearchPanel', 'sysUser.SysUserWindow',
	'sysUser.SysUserForm', 'sysUser.ChooseRoleWindow', 
	'sysUser.SysUserReadOnlyForm', 'sysUser.ChooseRoleGrid',
	'sysUser.SysPasswordWindow','sysUser.SysPasswordForm'],
	
	tabView: 'StaffServer.view.sysUser.SysUserMngr',
	
	sysUserWindow: null,
	sysUserForm: null,
	chooseRoleWindow: null,
	submitFlag: null,
	sysPasswordForm:null,
	sysPasswordWindow:null,
	refs : [ {
		ref : 'sysUserSearchPanel',
		selector : 'sysUserSearchPanel'
	}, {
		ref : 'sysUserGrid',
		selector : 'sysUserGrid'
	}, {
		ref : 'sysUserReadOnlyForm',
		selector : 'sysUserReadOnlyForm'
	}, {
		ref : 'chooseRoleGrid',
		selector : 'chooseRoleGrid'
	}],

	// 初始化执行语句
	init : function() {
		sysUserWindow = Ext.widget("sysUserWindow");
		sysPasswordWindow = Ext.widget("sysPasswordWindow");
		chooseRoleWindow = Ext.widget("chooseRoleWindow");
		sysUserForm = Ext.ComponentQuery.query('sysUserForm')[0];
		sysPasswordForm = Ext.ComponentQuery.query('sysPasswordForm')[0];
		
		// 控制事件
		this.control({
			'sysUserSearchPanel button[action=search]' : {
				click : this.search
			},
			'sysUserSearchPanel button[action=reset]' : {
				click : this.reset
			},
			'sysUserGrid button[action=saveSysUser]' : {
				click : this.saveSysUser
			},
			'sysUserGrid button[action=resetPassWord]' : {
				click : this.resetPassWord
			},
			
			
			'sysUserGrid button[action=updateSysUser]' : {
				click : this.updateSysUser
			},
			'sysUserGrid button[action=deleteSysUser]' : {
				click : this.deleteSysUser
			},
			'sysUserGrid button[action=chooseRole]' : {
				click : this.chooseRole
			},
			'sysUserWindow button[action=submit]' : {
				click : this.submitWindow
			},
			'sysUserWindow button[action=close]' : {
				click : this.closeWindow
			},
			'sysUserGrid': {
				itemdblclick: this.updateSysUser
			},
			'chooseRoleWindow button[action=submit]' : {
				click : this.submitChooseRole
			},
			'chooseRoleWindow button[action=close]' : {
				click : this.closeChooseRoleWindow
			}
			,
			'sysPasswordWindow button[action=submit]' : {
				click : this.submitPasswordWindow
			}
			,
			'sysPasswordWindow button[action=close]' : {
				click : this.closePasswordWindow
			}
		});
	},

	//searchPanel查询
	search : function() {
		var searchPanel = this.getSysUserSearchPanel();
		var grid = this.getSysUserGrid();
		grid.store.on('beforeload', function(store){
			var searchParams = searchPanel.getForm().getFieldValues();
			Ext.apply(store.proxy.extraParams, searchParams);
        });
		Ext.ComponentQuery.query('sysUserGrid > pagingtoolbar')[0].moveFirst();
	},
	
	//searchPanel重置
	reset: function(){
		var searchPanel = this.getSysUserSearchPanel();
		searchPanel.getForm().reset();
	},
	
	closePasswordWindow:function(){
		    sysPasswordWindow.hide();
	},
	submitPasswordWindow:function(){
		var $this=this;
		if(sysPasswordForm.getForm().isValid()){
			
			
			 showWaitMsg(); 
                Ext.Ajax.request({
                    url: 'sysUser/updateUserPassword',
                    params: sysPasswordForm.getForm().getValues(),
                    success: function(response){
                    	var resp = Ext.JSON.decode(response.responseText);
                        if (resp.success) {
                            Ext.Msg.alert('提示', '操作成功', function(){
                            	$this.search();
                            	$this.closePasswordWindow();
                            });
                        }
                        else {
                            Ext.Msg.alert('提示', resp.error);
                        }
                    },
                    failure: function(response){
                    	var resp = Ext.JSON.decode(response.responseText);
                        Ext.Msg.alert('提示', resp.error);
                    }
                });
		}
		
	},
	
	
	
	
	//新增
	saveSysUser: function(){
		Ext.ComponentQuery.query('sysUserForm field[name="userName"]')[0].setDisabled(false);
        Ext.ComponentQuery.query('sysUserForm field[name="password"]')[0].setDisabled(false);
        Ext.ComponentQuery.query('sysUserForm field[name="againPassword"]')[0].setDisabled(false);
		submitFlag = "save";
		sysUserWindow.setTitle("新增用户");
		sysUserWindow.show();
	},
	
	//更新
	updateSysUser: function(){
		var record = this.getSysUserGrid().getSelectionModel().getLastSelected();
        if (Ext.isEmpty(record)) {
            Ext.Msg.alert('提示', '请先选择要操作的记录!');
            return;
        }
        sysUserForm.loadRecord(record);
        Ext.ComponentQuery.query('sysUserForm field[name="userName"]')[0].setDisabled(true);
        Ext.ComponentQuery.query('sysUserForm field[name="password"]')[0].setValue('@@@@@@@@@@@').setDisabled(true);
        Ext.ComponentQuery.query('sysUserForm field[name="againPassword"]')[0].setValue('@@@@@@@@@@@').setDisabled(true);
        submitFlag = "update";
        sysUserWindow.setTitle("修改用户");
        sysUserWindow.show();
        
	},
	
	//更新
	resetPassWord: function(){
		var record = this.getSysUserGrid().getSelectionModel().getLastSelected();
		
        if (Ext.isEmpty(record)) {
            Ext.Msg.alert('提示', '请先选择要操作的记录!');
            return;
        }
        
        if(StaffServer.base.username!=record.data.userName){
        	 Ext.Msg.alert('提示', '只能对本人的密码进行修改');
            return;
        }
        sysPasswordForm.loadRecord(record);
        Ext.ComponentQuery.query('sysPasswordForm field[name="userName"]')[0].setDisabled(true);
        Ext.ComponentQuery.query('sysPasswordForm field[name="password"]')[0].setValue('');
        Ext.ComponentQuery.query('sysPasswordForm field[name="againPassword"]')[0].setValue('');
        submitFlag = "resetPassWord";
        sysPasswordWindow.setTitle("修改用户密码");
        sysPasswordWindow.show();
        
	},
	
	
	//删除
	deleteSysUser: function(){
		var $this = this;
		var record = this.getSysUserGrid().getSelectionModel().getLastSelected();
        if (Ext.isEmpty(record)) {
            Ext.Msg.alert('提示', '请先选择要操作的记录!');
            return;
        }
        Ext.MessageBox.confirm('请确认', '确认删除吗?', function(btn, text){
            if (btn == 'yes') {
                showWaitMsg(); 
                Ext.Ajax.request({
                    url: 'sysUser/deleteSysUser',
                    params: {
                       userId: record.get("userId")
                    },
                    success: function(response){
                    	var resp = Ext.JSON.decode(response.responseText);
                        if (resp.success) {
                            Ext.Msg.alert('提示', '操作成功', function(){
                            	$this.search();
                            });
                        }
                        else {
                            Ext.Msg.alert('提示', resp.error);
                        }
                    },
                    failure: function(response){
                    	var resp = Ext.JSON.decode(response.responseText);
                        Ext.Msg.alert('提示', resp.error);
                    }
                });
            }
        });
	},
	
	//提交表单
	submitWindow: function(){
		if (!sysUserForm.form.isValid()) {
            return;
        }
		var $this = this;
		var values = sysUserForm.getValues();
		var url;
		sysUserForm.getForm().submit({
			waitTitle: '系统提示',   
  			waitMsg: '正在处理,请稍候', 
			clientValidation: true,
		    url: submitFlag == 'save' ? 'sysUser/saveSysUser' : 'sysUser/updateSysUser',
		    params: {
		    	values: values
		    },
		    success: function(form, action) {
		    	Ext.Msg.alert('提示', "操作成功", function(){
		    		$this.closeWindow();
		    		$this.search();
		    	});
		    },
		    failure: function(form, action) {
		    	var resp = Ext.JSON.decode(action.response.responseText);
		    	Ext.Msg.alert('提示', resp.error);
		    }
		});
	},
	
	//关闭窗口
	closeWindow: function(){
		sysUserForm.getForm().reset();
		sysUserWindow.hide();
	},
	
	//分配角色
	chooseRole: function(){
		var record = this.getSysUserGrid().getSelectionModel().getLastSelected();
        if (Ext.isEmpty(record)) {
            Ext.Msg.alert('提示', '请先选择要操作的记录!');
            return;
        }
        this.getSysUserReadOnlyForm().loadRecord(record);
		chooseRoleWindow.setTitle("分配角色");
        chooseRoleWindow.show();
        var roleStore = this.getChooseRoleGrid().getStore();
        var roleSm = this.getChooseRoleGrid().getSelectionModel();
        roleStore.load({
            callback: function(roleRecords,options,success){
				Ext.Ajax.request({
		            url: 'sysUser/findRoleByUser',
		            params: {
                       userId: record.get("userId")
                    },
		            success: function(response){
						var selectRecordArr = new Array();
		                var resp = Ext.JSON.decode(response.responseText);
		                if (resp.success) {
							Ext.each(resp.root, function(userRoleRecord){
								Ext.each(roleRecords, function(roleRecord){
									if(roleRecord.get('roleId') == userRoleRecord.roleId){
										selectRecordArr.push(roleRecord);
									}
								});
							});
							roleSm.select(selectRecordArr);
		                }
		                else {
                            Ext.Msg.alert('提示', resp.error);
                        }
		            },
		           	failure: function(form, action) {
				    	var resp = Ext.JSON.decode(action.response.responseText);
				    	Ext.Msg.alert('提示', resp.error);
				    }
		        });            	
            }
        });
	},
	
	
	submitChooseRole: function(){
		var $this = this;
		var jsonArray = new Array();
		var records = this.getChooseRoleGrid().getSelectionModel().getSelection();
        if(records.length == 0){
           Ext.Msg.alert('提示', '请先选择要分配的角色!');
           return;
        }
         for (var i = 0; i < records.length; i++) {
            var record = records[i].data;
            jsonArray.push(record);
        };
        var userId = this.getSysUserReadOnlyForm().getRecord().get("userId");
        showWaitMsg(); 
		Ext.Ajax.request({
	        url: 'sysUser/chooseRole',
	        params: {
	        	userId: userId,
	           	roles: Ext.JSON.encode(jsonArray)
	        },
	        success: function(form, action) {
		    	Ext.Msg.alert('提示', "操作成功", function(){
		    		$this.closeChooseRoleWindow();
		    		$this.search();
		    	});
		    },
		    failure: function(form, action) {
		    	var resp = Ext.JSON.decode(action.response.responseText);
		    	Ext.Msg.alert('提示', resp.error);
		    }
	    });
	},
	
	
	closeChooseRoleWindow: function(){
		chooseRoleWindow.hide();
	}
	
	
});